package com.ezjie.ielts.module_word;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.application.YsApplication;
import com.ezjie.ielts.core.base.BaseBean;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.db.WordDao;
import com.ezjie.ielts.db.WordInstanceDao;
import com.ezjie.ielts.db.WordMeaningDao;
import com.ezjie.ielts.model.Eword;
import com.ezjie.ielts.model.EwordInstance;
import com.ezjie.ielts.model.EwordMeaning;
import com.ezjie.ielts.model.StudyRecord;
import com.ezjie.ielts.model.WordBean;
import com.ezjie.ielts.model.WordStudyStatus;
import com.ezjie.ielts.model.WordStudyingData;
import com.ezjie.ielts.task.WordTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.ListUtils;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.PlayAnimationUtils;
import com.ezjie.ielts.util.SpeechTTSUtil;
import com.ezjie.ielts.util.TextUtil;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.view.AutofitTextView;
import com.lidroid.xutils.exception.HttpException;
import com.umeng.analytics.MobclickAgent;

/**
 * 第一次学习界面
 * 
 * @author renyangyang
 *
 */
public class WordFirstStudyFragment extends Fragment implements OnClickListener {
	private static final String TAG = WordFirstStudyFragment.class.getSimpleName();
	private static final int REQUEST_CODE_DETAIL = 111;
	private AutofitTextView tv_word;// 当前单词
	private TextView tv_phonetic;// 音标
	private Button btn_thinked;// 想起来了
	private Button btn_unthinked;// 没想起来
	private TextView tv_examples;// 例句
	private LinearLayout ll_speak;// 播放按钮
	private LinearLayout ll_example;// 阅读句子

	private ImageView iv_speak;
	private ImageView iv_speakExample;
	private AnimationDrawable animation;
	private AnimationDrawable animation2;

	private WordStudyingData wordStudyingData;
	private List<WordBean> words;// 所有的单词
	private int currentPosition;// 当前位置
	private int total;// 总共单词
	private int passed;// 已经通过的

	private List<StudyRecord> studyRecords;
	private long startTimeMillis = 0;
	private WordDao wordDao;
	private WordInstanceDao wordInstanceDao;
	private WordMeaningDao wordMeaningDao;
	private WordTask mWordTask;
	private Context mContext;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		mContext = getActivity();
		studyRecords = new ArrayList<StudyRecord>();
		animation = PlayAnimationUtils.PlayWordAnimation(mContext);
		animation2 = PlayAnimationUtils.PlayWordAnimation(mContext);

		wordDao = new WordDao(mContext);
		wordInstanceDao = new WordInstanceDao(mContext);
		wordMeaningDao = new WordMeaningDao(mContext);
		mWordTask = new WordTask(mContext);

		SpeechTTSUtil.getInstance(mContext).init();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.layout_word_first_study, container, false);
		init(view);
		return view;
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_WORD_FIRST_DTUDY);
		MobclickAgent.onPause(mContext);
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_WORD_FIRST_DTUDY);
		MobclickAgent.onResume(mContext);
	}

	private void init(View view) {

		tv_word = (AutofitTextView) view.findViewById(R.id.tv_word);
		tv_word.setOnClickListener(this);
		tv_phonetic = (TextView) view.findViewById(R.id.tv_phonetic);
		btn_thinked = (Button) view.findViewById(R.id.btn_thinked);
		btn_unthinked = (Button) view.findViewById(R.id.btn_unthinked);
		btn_thinked.setOnClickListener(this);
		btn_unthinked.setOnClickListener(this);
		tv_examples = (TextView) view.findViewById(R.id.tv_examples);
		ll_speak = (LinearLayout) view.findViewById(R.id.ll_speak);
		ll_speak.setOnClickListener(this);
		ll_example = (LinearLayout) view.findViewById(R.id.ll_example);
		ll_example.setOnClickListener(this);
		iv_speak = (ImageView) view.findViewById(R.id.iv_speak);
		iv_speakExample = (ImageView) view.findViewById(R.id.iv_speakExample);

		if (mContext != null) {
			YsApplication myApplication = (YsApplication) getActivity().getApplication();
			wordStudyingData = myApplication.getWordStudyingData();
			if (wordStudyingData != null) {
				words = wordStudyingData.getWords();
				total = wordStudyingData.getTotal();
				passed = wordStudyingData.getPassed();

				if (words != null && words.size() > 0) {
					initParentProgress();
				}
			}
			initWord();
		}
	}

	private void initParentProgress() {
		// 控制父view显示进度
		Activity parentActivity = getActivity();
		if (parentActivity instanceof WordStudyManagerActivity) {
			WordStudyManagerActivity activity = (WordStudyManagerActivity) parentActivity;
			activity.showProgress(total, passed);
		}
	}

	private void changeView() {
		// 控制父view显示详情
		Activity parentActivity = getActivity();
		if (parentActivity instanceof WordStudyManagerActivity) {
			WordStudyManagerActivity activity = (WordStudyManagerActivity) parentActivity;
			SpeechTTSUtil.getInstance(mContext).pause();
			activity.showView(WordStudyManagerActivity.SHOW_DETAIL);
		}
	}

	private void initWord() {
		if (mContext != null && words != null && words.size() > 0 && passed < total) {
			// 取出 第一个 is_passed为false的
			getUnPassed();
			startTimeMillis = System.currentTimeMillis();
			if (currentPosition < words.size()) {
				WordBean wordBean = words.get(currentPosition);
				Eword eword = wordDao.findByWordId(wordBean.getWid());
				List<EwordInstance> ewordInstances = wordInstanceDao.findByWordId(wordBean.getWid());
				List<EwordMeaning> ewordMeanings = wordMeaningDao.findByWordId(wordBean.getWid());
				if (eword != null) {
					wordBean.setWord(eword.word);
					wordBean.setPhonetic(eword.en_phonetic);
					wordBean.setInstances(ListUtils.transferInstanceList(ewordInstances));
					wordBean.setMeans(ListUtils.transferMeanList(ewordMeanings));
					tv_word.setText(Html.fromHtml(eword.word));
					if (!TextUtils.isEmpty(eword.en_phonetic) && !"[]".equals(eword.en_phonetic)) {
						ll_speak.setVisibility(View.VISIBLE);
						tv_phonetic.setText(Html.fromHtml(eword.en_phonetic));
					} else {
						ll_speak.setVisibility(View.INVISIBLE);
					}
					String example = ListUtils.getExampleStrFor1ByList(wordBean.getInstances());

					tv_examples.setText(TextUtil.transferBoldWhiteWord(wordBean.getWord(), example));

					initParentProgress();
				}

			}

		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		// TODO Auto-generated method stub
		super.onHiddenChanged(hidden);
		if (!hidden) {
			// 当切换界面的时候 hidden为false 切换下个单词
			initWord();
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		// 销毁前保存列表
		YsApplication myApplication = (YsApplication) getActivity().getApplication();
		myApplication.setWordStudyingData(wordStudyingData);

	}

	@Override
	public void onViewStateRestored(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewStateRestored(savedInstanceState);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.navi_back_btn:
			onBackPressed();
			break;
		case R.id.btn_thinked:
			if (mContext != null && words != null && currentPosition < words.size() && wordStudyingData != null) {
				WordBean wordBean = words.get(currentPosition);
				wordBean.setIs_passed(true);
				passed++;

				// 学习记录
				long endTimeMillis = System.currentTimeMillis();
				int sec = (int) ((endTimeMillis - startTimeMillis) / 1000) + 1;
				StudyRecord studyRecord = new StudyRecord();
				studyRecord.setWid(wordBean.getWid());
				studyRecord.setIs_passed(true);
				studyRecord.setSec(sec);
				studyRecords.add(studyRecord);

				YsApplication myApplication = (YsApplication) getActivity().getApplication();
				myApplication.setStudyRecords(studyRecords);
				myApplication.setWords(words);
				myApplication.setWordBean(wordBean);
				WordStudyStatus wordStudyStatus = new WordStudyStatus();
				wordStudyStatus.setMax(total);
				wordStudyStatus.setProgress(passed);
				wordStudyStatus.setStatus(wordStudyingData.getStatus());
				wordStudyStatus.setWgid(wordStudyingData.getWgid());
				myApplication.setWordStudyStatus(wordStudyStatus);

				changeView();

			}
			break;
		case R.id.btn_unthinked:
			if (mContext != null && words != null && currentPosition < words.size() && wordStudyingData != null) {
				WordBean wordBean = words.get(currentPosition);
				wordBean.setIs_passed(false);
				// 移动到最后
				words.remove(currentPosition);
				words.add(wordBean);

				// 学习记录
				long endTimeMillis = System.currentTimeMillis();
				int sec = (int) ((endTimeMillis - startTimeMillis) / 1000) + 1;
				StudyRecord studyRecord = new StudyRecord();
				studyRecord.setWid(wordBean.getWid());
				studyRecord.setIs_passed(false);
				studyRecord.setSec(sec);
				studyRecords.add(studyRecord);

				YsApplication myApplication = (YsApplication) getActivity().getApplication();
				myApplication.setStudyRecords(studyRecords);
				myApplication.setWords(words);
				myApplication.setWordBean(wordBean);
				WordStudyStatus wordStudyStatus = new WordStudyStatus();
				wordStudyStatus.setMax(total);
				wordStudyStatus.setProgress(passed);
				wordStudyStatus.setStatus(wordStudyingData.getStatus());
				wordStudyStatus.setWgid(wordStudyingData.getWgid());
				myApplication.setWordStudyStatus(wordStudyStatus);

				changeView();

			}
			break;
		case R.id.ll_speak:
		case R.id.tv_word:
			iv_speak.setImageDrawable(animation);
			animation.start();
			if (animation2 != null && animation2.isRunning()) {
				animation2.selectDrawable(0);
				animation2.stop();
			}
			String string = tv_word.getText().toString();
			if (!TextUtils.isEmpty(string)) {
				SpeechTTSUtil.getInstance(mContext).speak(string, animation);
			}
			break;
		case R.id.ll_example:
			iv_speakExample.setImageDrawable(animation2);
			animation2.start();
			if (animation != null && animation.isRunning()) {
				animation.selectDrawable(0);
				animation.stop();
			}
			String examples = tv_examples.getText().toString();
			if (!TextUtils.isEmpty(examples)) {
				SpeechTTSUtil.getInstance(mContext).speak(examples, animation2);
			}
			break;
		default:
			break;
		}

	}

	private void getUnPassed() {
		if (words != null && words.size() > 0) {
			for (int i = 0; i < words.size(); i++) {
				WordBean wordBean = words.get(i);
				if (!wordBean.isIs_passed()) {
					currentPosition = i;
					break;
				}
			}
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_DETAIL) {
			if (data != null) {
				boolean isOver = data.getBooleanExtra("isOver", false);
				if (isOver) {
					SpeechTTSUtil.getInstance(mContext).close();
					getActivity().finish();
					return;
				}
			}
			if (words != null) {
				initWord();
			}
		}
	}

	public void onBackPressed() {
		if (mContext != null) {

			View view = LayoutInflater.from(mContext).inflate(R.layout.layout_rob_warn_dialog, null);

			final Dialog dialog = new Dialog(mContext, R.style.customDialog);
			dialog.setCanceledOnTouchOutside(false);
			dialog.setContentView(view);
			dialog.show();

			TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
			tv_content.setText(R.string.word_first_exit_msg);
			LinearLayout ll_layout1 = (LinearLayout) view.findViewById(R.id.ll_layout1);
			LinearLayout ll_layout2 = (LinearLayout) view.findViewById(R.id.ll_layout2);
			ll_layout1.setVisibility(View.VISIBLE);
			ll_layout2.setVisibility(View.GONE);

			Button btn_yes = (Button) view.findViewById(R.id.btn_yes);
			Button btn_no = (Button) view.findViewById(R.id.btn_no);
			btn_no.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (mContext != null && dialog != null && dialog.isShowing()) {
						dialog.cancel();
					}
				}
			});
			btn_yes.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (mContext != null && dialog != null && dialog.isShowing()) {
						dialog.cancel();
						// 友盟统计
						MobclickAgent.onEvent(mContext, "word_learning_backBtn");
						// 保存进度
						saveProgress();
					}

				}
			});

		}

	}

	private void saveProgress() {

		if (mContext != null && wordStudyingData != null) {
			if (!NetworkUtil.isNetworkAvailable(mContext)) {
				AppUtil.showToast(mContext, R.string.no_network);
				return;
			}

			mWordTask.saveProgress(wordStudyingData.getWgid() + "", "true", wordStudyingData.getStatus() + "",
					JSON.toJSONString(studyRecords), new HttpRequestAbstractCallBack(mContext,true) {
						@Override
						public void onStartCallBack() {
							super.onStartCallBack();
							AppUtil.showProgressDialog(mContext);
						}

						@Override
						public void onSuccessCallBack(String result) {
							super.onSuccessCallBack(result);
							LogUtils.d(result);
							AppUtil.dismissProgressDialog();
							try {
								BaseBean baseBean = JSON.parseObject(result, BaseBean.class);
								if (baseBean != null && 200 == baseBean.getStatus_code()) {
									// 提交成功
									if (getActivity() != null) {
										SpeechTTSUtil.getInstance(mContext).close();
										getActivity().finish();
									}
								} else {
									if (getActivity() != null) {
										AppUtil.showToast(mContext, R.string.load_net_data_failure);
									}
								}
							} catch (Exception e) {
								LogUtils.d("json数据异常");
								LogUtils.exception(e);
							}
						}

						@Override
						public void onFailureCallBack(HttpException error, String msg) {
							super.onFailureCallBack(error, msg);
							LogUtils.e(msg);
							AppUtil.dismissProgressDialog();
							AppUtil.showToast(mContext, R.string.load_net_data_failure);
						}
					});

		}

	}

}
